<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Bookcase extends BaseModel
{
    use HasFactory;

    const CREATED_AT='create_time';
    const UPDATED_AT='change_time';

    protected $table = 'bookcase';


    /**
     * 根据编号获取柜子id
     */
    public static function getBoocaseIdByCabCode($cab_code){
        return self::where('cab_code' , $cab_code)->where('is_del' , 1)->value('id');
    }


     /**
     *  机柜添加
     * @param $data 添加的数据
     */
    public function add($data){
        $this->name = $data->name;
        $this->cab_code = $this->getCabCode();
        $this->stack_number = 'B'.getRndNumber(8);
        $this->address = $data->address;
        $this->intro = $data->intro;
        $this->manage_id = $data->manage_id;
        $this->is_del = 1;

        return  $this->save();
    }
    /**
     * 获取机柜编号
     */
    public function getCabCode(){
        $cab_code = $this->lockForUpdate()->where('is_del' , 1)->max('cab_code');
        if(empty($cab_code)) return '002800001';
        $cab_code =  ++ $cab_code;
        return sprintf("%09d", $cab_code);//生成9位数，不足前面补0
    }

    /**
     *  机柜修改
     * @param $data 添加的数据
     */
    public function change($data){
        $res = $this->where('is_del' , 1)->find($data['id']);
        if(!$res){
            throw new Exception('数据获取失败');
        }

        $res->name = $data->name;
        $res->address = $data->address;
        $res->intro = $data->intro;
        return  $res->save();
    }


    /**
     * 判断机柜名称是否已经存在
     * @param name 机柜名称
     * @param id 机柜id   可选，主要是用于修改
     */
    public function bookcaseNameIsExists($name , $id = null){
        $res = $this->where('name' , $name)->where(function($query) use($id){
                if(!empty($id)){
                    $query->where('id' , '<>' , $id);
                }
        })->where('is_del' , 1)->first();
        return $res;
    }

    /**
     * 判断是否有展览，修改柜子展览标识
     * @param  $bookcase_id 柜子id
     */
    public function isConfigChange($bookcase_id){
        $is_config = BookcaseExhibition::where('bookcase_id' , $bookcase_id)->first();
        $res = $this->where('id' , $bookcase_id)->first();
        if(empty($res)){
            return false;
        }
        $is_config = $is_config ? 1 : 2;
        if ($res->is_config != $is_config) {
            $res->is_config = $is_config;
            $res->save();
        }
    }

    
}
